package 题组;

/**
 * @author 挚爱之夕
 * @date 2021/9/7 - 09 - 07 - 20:43
 * @Description: 题组
 * @Version: 1.0
 */
public class _003_分割平衡字符串 {
    /*
    返回最大平衡串数量，RL是一个，RRLL也是
    两边R和L相等
     */
    public static void main(String[] args) {
        String s = "RLRRLLRL";
        String s1 = "RLLLLRRRLR";
        int answer = balancedStringSplit1(s);
        System.out.println(answer);
    }
    //自己写的,部分案例存在越界问题
    public static int balancedStringSplit(String s) {
        int max = 0;
        char begin = s.charAt(0);
        int leftCount = 1;
        int left = 1,right=left;
        while(right<s.length()){
            while(s.charAt(left)==begin){
                leftCount++;
                left++;
            }
            right = left+1;
            while(right<s.length()&&s.charAt(right)!=begin){
                if((right-left+1)==leftCount){
                    right++;//使right指向新的开始
                    break;
                }

                right++;
            }

            max++;
            if(right>=s.length())
                break;
            leftCount=1;
            begin = s.charAt(right);
            left = right+1;
        }

        return max;
    }
    //贪心
    public static int balancedStringSplit1(String s) {
        int ans = 0, d = 0;
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if (ch == 'L') {
                d++;
            } else {
                d--;
            }
            if (d == 0) {
                ans++;
            }
        }
        return ans;
    }
}
